﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using Home.Domain.Entities;
using Home.WebUI.Areas.Admin.Models;
using Home.WebUI.Areas.Admin.Models.NewsViewModel;
using Home.WebUI.Models;
using Omu.ValueInjecter;

namespace Home.WebUI.Areas.Admin.Controllers
{
    public class NewsController : Controller
    {
        private EFDbContext db = new EFDbContext();
        //
        // GET: /Admin/News/

        #region 列表
        public ActionResult Index(IndexViewModel model, int page = 1)
        {
            int pageSize = 15;
            var news = db.News.Include(n => n.PNews).OrderByDescending(c => c.CreateDate).Skip((page - 1) * pageSize).Take(pageSize);
            if (!string.IsNullOrEmpty(model.Search))
            {
                news = news.Where(c => c.Title.Contains(model.Search));
            }
            model.News = news;
            model.PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = pageSize, TotalItems = db.News.Count() };
            return View(model);
        }
        public ActionResult Create()
        {
            News model = new News();
            model.CreateDate = DateTime.Now;
            PNewsDropDownList();
            return View(model);
        }
        [HttpPost, ValidateInput(false)]
        public ActionResult Create(News model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.News.Add(model);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (DataException)
            {
                TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            }
            PNewsDropDownList();
            return View(model);
        }
        public ActionResult Edit(int id)
        {
            News model = db.News.Find(id);
            PNewsDropDownList(model.PNewsId);
            return View(model);
        }
        [HttpPost, ValidateInput(false)]
        public ActionResult Edit(News model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    News content = new News();
                    content.Id = model.Id;
                    db.News.Attach(content);
                    content.InjectFrom(model);
                    //ObjectMapperManager.DefaultInstance.GetMapper<News, News>().Map(model, content);//model的值传给content
                    db.SaveChanges();
                    TempData["Tip"] = new TipModel(1, "保存成功");
                    return RedirectToAction("Index");
                }
            }
            catch (DataException)
            {
                TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            }
            PNewsDropDownList();
            return View(model);
        }
        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add delete logic here    
                if (Request.IsAjaxRequest())
                {
                    News content = new News();
                    content.Id = id;
                    db.Entry(content).State = EntityState.Deleted;
                    //EntityState stateafter = db.Entry(content).State;//Deleted状态     
                    int result = db.SaveChanges();
                    return Content("0");
                }
                else
                {
                    return Content("-1");
                }
            }
            catch
            {
                return Content("-1");
            }
        } 
        #endregion

        #region 分类
        public ActionResult PNewsIndex()
        {

            return View(db.PNews.OrderByDescending(n => n.Sort).ToList());
        }

        public ActionResult PNewsCreate()
        {
            return View();
        }
        [HttpPost]
        public ActionResult PNewsCreate(PNews model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    int? sort = db.PNews.Select(p => p.Sort).Max();
                    model.Sort = sort == null ? 1 : sort + 1;
                    db.PNews.Add(model);
                    db.SaveChanges();
                    return RedirectToAction("PNewsIndex");
                }
            }
            catch (DataException)
            {
                TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            }
            return View(model);
        }
        public ActionResult PNewsEdit(int id)
        {
            return View(db.PNews.Find(id));
        }
        [HttpPost]
        public ActionResult PNewsEdit(PNews model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    PNews content = new PNews();
                    content.Id = model.Id;
                    db.PNews.Attach(content);
                    content.InjectFrom(model);
                    //ObjectMapperManager.DefaultInstance.GetMapper<PNews, PNews>().Map(model, content);//model的值传给content
                    db.SaveChanges();
                    TempData["Tip"] = new TipModel(1, "保存成功");
                    return RedirectToAction("PNewsIndex");
                }
            }
            catch (DataException)
            {
                TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            }
            return View(model);
        }

        public ActionResult PNewsUp(int id)
        {
            PNews content = db.PNews.Find(id);
            PNews contentup = db.PNews.Where(c => c.Sort > content.Sort).OrderBy(c => c.Sort).FirstOrDefault();
            if (contentup == null)
            {
                return Redirect(Request.UrlReferrer.ToString());
            }
            db.PNews.Attach(content);
            content.Sort = contentup.Sort;
            db.PNews.Attach(contentup);
            contentup.Sort = contentup.Sort - 1;
            db.SaveChanges();
            return Redirect(Request.UrlReferrer.ToString());
        }
        [HttpPost]
        public ActionResult PNewsDelete(int id)
        {
            try
            {
                // TODO: Add delete logic here    
                if (Request.IsAjaxRequest())
                {
                    PNews content = db.PNews.Find(id);
                    int newsNumer = db.News.Count(n => n.PNews.Id == content.Id);
                    //int newsNumer = content.News.Count();
                    if (newsNumer > 0)
                    {
                        return Content(newsNumer.ToString());
                    }
                    db.PNews.Remove(content);
                    //EntityState stateafter = db.Entry(content).State;//Deleted状态     
                    int result = db.SaveChanges();
                    return Content("0");
                }
                else
                {
                    return Content("-1");
                }
            }
            catch
            {
                return Content("-1");
            }
        } 
        #endregion

        /// <summary>
        /// 分类下拉
        /// </summary>
        /// <param name="selectedPNews">选中项</param>
        private void PNewsDropDownList(object selectedPNews=null)
        {
            SelectList items = new SelectList(db.PNews.OrderByDescending(p => p.Sort).ToList(), "Id", "Title",selectedPNews);
            ViewBag.PNews = items;
        }

        protected override void Dispose(bool disposing) 
        { 
            db.Dispose(); 
            base.Dispose(disposing); 
        }

    }
}